<template>
    <div class="app-container">
        <el-form :model="queryParam" ref="queryForm" :inline="true">
            <el-form-item label="真实姓名：">
                <el-input v-model="queryParam.realName" clearable></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm" v-has-perm="['user:userPoint:page']">查询</el-button>
                <el-button @click="clearForm">重置</el-button>
                <el-button type="primary" class="link-left" @click="userExport">导出
                </el-button>
                <el-popover placement="bottom" trigger="click" :width="240">
                    <template #reference>
                        <el-button type="primary" class="link-left">导入
                        </el-button>
                    </template>
                    <div class="wdd-popover-content">
                        <a target="_blank"
                            href="https://tongzhou-exam.oss-cn-beijing.aliyuncs.com/template/point/%E7%A7%AF%E5%88%86%E4%BF%AE%E6%94%B9%E6%A8%A1%E6%9D%BF.xlsx"
                            style="float: left; margin-left: 5px">
                            <el-button type="success">Excel 模板</el-button>
                        </a>
                        <el-upload style="float: left; margin-left: 5px" accept=".xlsx"
                            action="/api/userPoint/point/import" :show-file-list="false" :on-progress="uploadProgress"
                            :on-success="uploadExcelSuccess" :on-error="uploadError">
                            <el-button type="success" class="link-left">Excel 导入</el-button>
                        </el-upload>
                    </div>
                </el-popover>
            </el-form-item>
        </el-form>

        <el-table :data="tableData" border fit style="width: 100%;" highlight-current-row>
            <el-table-column prop="id" label="id" align="center" />
            <el-table-column prop="realName" label="真实姓名" align="center" />
            <el-table-column prop="totalPoint" label="总积分" align="center" />
            <el-table-column prop="remainPoint" label="剩余积分" align="center" />
            <!-- <el-table-column prop="createTime" label="创建时间" width="160px" align="center" /> -->
            <el-table-column label="操作" align="center">
                <template #default="{ row }">
                    <el-button @click="show(row.id)" size="small" class="wdd-button-mini">编辑
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-dialog v-model="showDialog" width="40%">
            <el-form ref="form" :model="form" label-width="200px">
                <el-form-item label="剩余积分：" prop="remainPoint" required>
                    <el-input v-model="form.remainPoint"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="credentialSearch">提交</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParam.pageIndex"
            v-model:limit="queryParam.pageSize" @pagination="search" />
    </div>
</template>

<script>
import { userpointPage, userpointExport, updatePoint, userpointimport } from '@/api/user';
import { tree } from '@/api/department';

export default {
    name: 'userPointList',
    data() {
        return {
            VITE_APP_RESOURCE_URL: import.meta.env.VITE_APP_RESOURCE_URL,
            queryParam: {
                pageIndex: 1,
                pageSize: 10,
                realName: null
            },
            form: {
                id: null,
                remainPoint: null
            },
            tableData: [],
            total: 0,
            canLoad: true,
            showDialog: false
        };
    },
    mounted() {
        this.init();
        this.canLoad = false;
    },
    activated() {
        this.init();
    },
    deactivated() {
        this.canLoad = true;
    },
    methods: {
        init() {
            if (!this.canLoad) {
                return;
            }
            this.search();
        },
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            console.log(this.ids)
        },
        search() {
            userpointPage(this.queryParam).then(data => {
                const re = data.response;
                this.tableData = re.list;
                this.tableData.createTime = this.timestampToYMDHMS(this.tableData.createTime);
                this.total = re.total;
                this.queryParam.pageIndex = re.pageNum;
            });
        },
        //时间转换
        timestampToYMDHMS(timestamp) {
            const date = new Date(timestamp);
            const year = date.getUTCFullYear();
            const month = ('0' + (date.getUTCMonth() + 1)).slice(-2); // 月份是从0开始的
            const day = ('0' + date.getUTCDate()).slice(-2);
            const hours = ('0' + date.getUTCHours()).slice(-2);
            const minutes = ('0' + date.getUTCMinutes()).slice(-2);
            const seconds = ('0' + date.getUTCSeconds()).slice(-2);
            return `${year}${month}${day} ${hours}:${minutes}:${seconds}`;
        },
        submitForm() {
            this.queryParam.pageIndex = 1;
            this.search();
        },
        clearForm() {
            this.queryParam = {
                realName: null,
                pageIndex: 1,
                pageSize: 10
            };
            this.search();
        },
        userExport() {
            userpointExport(this.queryParam).then(res => {
                let blob = new Blob([res], { type: "application/vnd.ms-excel" });
                // 创建 href 超链接，点击进行下载
                window.URL = window.URL || window.webkitURL;
                let href = URL.createObjectURL(blob);
                let downA = document.createElement("a");
                downA.href = href;
                downA.download = '积分列表';
                downA.click();
                // 销毁超连接
                window.URL.revokeObjectURL(href);
            });
        },
        uploadProgress() {
            this.loading = this.$loading({
                lock: true,
                text: '文件上传中…',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.5)'
            });
        },
        uploadExcelSuccess(re, file) {
            this.loading.close();
            if (re.code === 1) {
                this.search();
                window.location.href = re.response;
            } else {
                this.$message.error(re.message);
            }
        },
        uploadError() {
            this.loading.close();
            this.$message.error('文件上传失败，请检查文件大小或文件格式');
        },
        show(row) {
            console.log(row)
            this.form.id = row
            this.showDialog = true
        },
        credentialSearch() {
            updatePoint(this.form).then(res => {
                if (res.code == 1) {
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                    this.search();
                    this.showDialog = false
                } else {
                    this.$message({
                        message: res.response,
                        type: 'warning'
                    });
                }
            })
        }

    }
};
</script>